<?php
namespace app\api\controller;

use app\api\model\DofunData;
use app\api\controller\Offer;
use think\Log;

class Dofun
{
    public function index()
    {
        $url = 'http://cashify.dofunapps.com/export/offer?access=188&token=8a88cd6e6704d9dd54a2dac7d5546cf5&size=100&os=ios';
        $a = file_get_contents($url);
        dump(json_decode($a,true));
    }

    /*
     * 获取offer数据
     */
    public function getData()
    {
        $data_mod = new DofunData;
        //$total = 1000;
        $limit = 100;//获取条数
        $access = '188';
        $token = '8a88cd6e6704d9dd54a2dac7d5546cf5';
        $url = 'http://cashify.dofunapps.com/export/offer?adtype=1&access='.$access.'&token='.$token.'&size='.$limit.'&os=ios';//只获取Ios的单子
        $i = $j = $m = 0;
        $new_offerids = $update_offerids = '';
        set_time_limit(0);
        echo '开始:'.date("H:i:s")."<br />";
        $get_str = file_get_contents($url);
        $get_content = json_decode($get_str,true);//dump($get_content);exit;
        echo '获取数据：'.date("H:i:s")."<br />";

        $all_offerids = $update_data = $insert_data = array();
        if($get_content['status'] == 1){
            $data_arr = $get_content['data'];
            if(!empty($data_arr)){
                //轮询所有数据
                foreach($data_arr as $k=>$v){
                    /*if($v['bid'] < 1) {
                        continue;
                    }*/
                    $all_offerids[] = $v['offerId'];
                    //处理返回数据的'conversionFlow '键后面带空格的问题。
                    if(isset($v['conversionFlow '])){
                        $v['conversionFlow'] = $v['conversionFlow '];
                        unset($v['conversionFlow ']);
                    }

                    $offer_info = $data_mod->find($v['offerId']);
                    if(!empty($offer_info)){ //该offer已经存在,对比信息是否有更新
                        $offer_info = $offer_info->toArray();
                        $diff_arr = array();//对比新获取的数据和原来保存的数据

                        if($offer_info['bid'] != $v['bid']){ //如果数据有更新，则获取更新数据
                            $diff_arr['update_time'] = time();
                            $diff_arr['offerId'] = $v['offerId'];
                            $diff_arr['bid'] = $v['bid'];
                            $diff_arr['offer_status'] = 2;
                            $update_data[] = $diff_arr;
                            $i++;//更新数
                            $update_offerids .= $v['offerId'].',';//记录日志用的
                        } else {
                            $j++;//已有数
                        }


                    } else { //该offer不存在,获取新增数据
                        $time = time();
                        $v['update_time'] = $time;
                        $v['create_time'] = $time;
                        $insert_data[] = $v;
                        $new_offerids .=$v['offerId'].',';//记录日志用的

                        $m++;//新增数
                    }
                }
            }
        }

        echo '循环数据：'.date("H:i:s")."<br />";
        //新增记录
        if(!empty($insert_data))
        {
            $insert_res = $data_mod->saveAll($insert_data,false);

        }

        //更新记录
        if(!empty($update_data))
        {
            $update_res = $data_mod->isUpdate()->saveAll($update_data);
            //dump($update_res);
        }

        //将本次没有获取的单子全部做下线处理
        $data_mod->whereNotIn('offerId',$all_offerids)->where(array('offer_status'=>1))->update(array('update_time'=> time(),'offer_status'=> 3));

        //记录日志
        save_apilog('add_offersId:'.$new_offerids,'dofun');
        save_apilog('update_offersId:'.$update_offerids,'dofun');

        echo '插入数据：'.date("H:i:s")."<br />";

        echo '更新数据:'.$i."<br />";
        echo '已有数据:'.$j."<br />";
        echo '新增数据:'.$m."<br />";
    }


    /*
     * 推送offer
     */
    public function postOffer()
    {
        $offer_obj = new Offer();
        $advertiser_id = 72;
        $data_mod = new DofunData;
        $update_data = array();

        //$info = $data_mod->limit(1)->find()->toArray();
        $insert_data = $data_mod->where(array('offer_id'=>0,'offer_status'=>0))->select()->toArray();//dump($insert_data);exit;
        if(empty($insert_data))
        {
            echo 'No offers add';
            exit;
        }
        foreach($insert_data as $info){
            //0.2以下的单子不导入
            /*if($info['bid'] < 1) {
                continue;
            }*/
            $os = $info['os'] == 'ios' ? 0 : 1;
            $osv = $info['minVersion'];
            if($os == 0)//ios系统
            {
                $destination_url = $info['clickUrl'].'&os=0&osv='.$osv.'&idfa={ios_idfa}&pb={click_id}&subid={aff_id}';
            } else {//android系统
                $destination_url = $info['clickUrl'].'&os=1&osv='.$osv.'&udid={android_id}&gaid={google_aid}&pb={click_id}&subid={aff_id}';
            }

            $preview_url = empty($info['preview_url']) ? (($info['os'] == 'ios' && !empty($info['pack'])) ? 'https://itunes.apple.com/cn/app/id'.$info['pack'] : '') : $info['preview_url'];

            $countries = explode(',',$info['country2B']);
            $os_version = empty($info['minVersion']) ? 0 : (($info['os'] == 'ios' && $info['minVersion'] < 5.0) ? 0 : $info['minVersion']);

            $param = array(
                'name' => $info['name'],
                'preview_url' => $preview_url,
                'destination_url' => $destination_url,
                'description' => $info['description'],
                'offer_id' => $info['offerId'],
                'price' => $info['bid'],
                'os' => $info['os'],
                'os_version' =>format_ver($os_version),
                'country' => $countries,
                'status' => 1,
            );
            $res = $offer_obj->addOffer($param,$advertiser_id);
            //dump($res);
            if($res['code'] != 0){
                save_apilog('post_fail:'.json_encode($res),'dofun');
                continue;
            }

            $update_data = array('offer_id'=> $res['data']['offer']['id'],'offer_status'=> 1);
            $data_mod->where(array('offerId'=> $info['offerId']))->update($update_data);

        }

    }

    /*
     * 更新offer
     */
    public function updateOffer()
    {
        $offer_obj = new Offer();
        $advertiser_id = 72;
        $data_mod = new DofunData;
        $update_data = array();

        //$update_offerid_list = $data_mod->select($update_offerids)->toArray();
        $update_offerid_list = $data_mod->where(array('offer_id'=>array('>',0),'offer_status'=>2))->field('offerId,bid,offer_id')->select()->toArray();//dump($update_offerid_list);exit;
        //
        if(empty($update_offerid_list))
        {
            echo 'No offers update';
            exit;
        }
        foreach($update_offerid_list as $info){
            $offer_res = $offer_obj->updateOfferPrice($info['offer_id'],$info['bid']);
            if($offer_res['code'] != 0)
            {
                save_apilog('update_offer_price:'.json_encode($offer_res),'dofun');
            }
            //dump($res);
            $update_data[] = array('offerId'=> $info['offerId'],'offer_status'=> 1);

        }
        //dump($info);


        $res = $data_mod->isUpdate()->saveAll($update_data);

    }

    /*
     * 更新offer状态
     */
    public function updateOfferStatus()
    {
        //$ids = array(127);
        $offer_obj = new Offer();

        $data_mod = new DofunData;
        //将单子下线
        $where = array(
            'offer_status'=> 3,
        );
        $list = $data_mod->field('offer_id')->where($where)->limit(100)->select()->toArray();
        $ids = array();
        foreach($list as $id){
            $ids[] = $id['offer_id'];
        }
        if(!empty($ids)){
            $res = $offer_obj->pausedOffer($ids);
            if($res['code'] != 0){
                save_apilog('paused_offer:'.json_encode($res),'dofun');
            }
            $data_mod->whereIn('offer_id',$ids)->update(array('offer_status'=> -1));
        }



    }

    /*
     * 上传logo
     */
    public function uploadLogo()
    {
        $off_id = 525;
        $path = 'http://lh3.googleusercontent.com/m-WE4Y6okT0VHIyKpO44z-m8fpK4fzz-wZMiT5AfCyM-9yKjKo39N7L9ybgDbgOZVw=w300';
        $off_obj = new Offer();
        $res = $off_obj->uploadLogo($off_id,$path);

        dump($res);
    }

}


